import 'package:flutter/material.dart';
import 'package:itoken/Components/CRouter.dart';
import 'package:itoken/Components/CStore.dart';
import 'package:itoken/Store/SAddress.dart';
import 'package:itoken/abi/USDT.dart';
import 'package:itoken/tools/wei.dart';

// import 'package:itoken/tools/eth.dart';
import 'package:provider/provider.dart';

import 'package:http/http.dart';
import 'package:web3dart/web3dart.dart';

class _IStore with ChangeNotifier {
  String _addr = "0x27a3084C006CD9212828E57020C87D2036b1898C";
  String _address = "";
  String _private = "";
  Web3Client _ethClient;
  String _eth = "0";

  get eth => _eth;
  String _usdt = "0";
  get usdt => _usdt;

  _IStore({@required String address, @required String private}) {
    _private = private;
    _address = address;
    String apiUrl =
        "https://ropsten.infura.io/v3/2521b8df3336431986c5b6abbe2b8f53";

    _ethClient = new Web3Client(apiUrl, Client());
    reload();
  }

  Future reload() async {
    // print(_private);
    final credentials = await _ethClient.credentialsFromPrivateKey("$_private");
    final address = await credentials.extractAddress();

    EtherAmount data = await _ethClient.getBalance(address);
    _eth = Tools.weiTo("${data.getInWei}", 18);
    print(_eth);
    await getUSDT();
    notifyListeners();
    // print(_eth);
  }

  Future sendTransaction() async {
    // print(_private);
    final credentials = await _ethClient.credentialsFromPrivateKey("$_private");
    int data = Tools.toWei("0.01", 18);
    print(data);
    String hash = await _ethClient.sendTransaction(
      credentials,
      Transaction(
        to: EthereumAddress.fromHex(_addr),
        gasPrice: EtherAmount.inWei(BigInt.one),
        maxGas: 100000,
        value: EtherAmount.fromUnitAndValue(
          EtherUnit.wei,
          BigInt.from(data),
        ), //0.1
      ),
      // chainId: 3,
      fetchChainIdFromNetworkId: true,
    );
    print(hash);
    getTransactionReceipt(hash);
  }

  Future getTransactionReceipt(String hash) async {
    var res = await _ethClient.getTransactionByHash(hash);
    // print(res.blockHash);
    if (res.blockHash == null) {
      getTransactionReceipt(hash);
    } else {
      await reload();
    }
  }

  getUSDT() async {
    final EthereumAddress contractAddr = EthereumAddress.fromHex(
      contractAddressUSDT,
    );
    final contract = DeployedContract(
      ContractAbi.fromJson(usdtAbi, 'MetaCoin'),
      contractAddr,
    );
    final balanceFunction = contract.function('balanceOf');
    final EthereumAddress addr = EthereumAddress.fromHex(
      _address,
    );
    final balance = await _ethClient
        .call(contract: contract, function: balanceFunction, params: [addr]);
    _usdt = Tools.weiTo("${balance.first}", 6);
    print(_usdt);
    // print('We have ${balance.first} MetaCoins');
  }

  sendUSDT() async {
    final EthereumAddress contractAddr = EthereumAddress.fromHex(
      contractAddressUSDT,
    );
    final contract = DeployedContract(
      ContractAbi.fromJson(usdtAbi, 'MetaCoin'),
      contractAddr,
    );
    final transferFunction = contract.function('transfer');
    final EthereumAddress addr = EthereumAddress.fromHex(
      _addr,
    );
    final credentials = await _ethClient.credentialsFromPrivateKey("$_private");
    int data = Tools.toWei("1",6);
    // print(data);
    String hash = await _ethClient.sendTransaction(
      credentials,
      Transaction.callContract(
        contract: contract,
        function: transferFunction,
        parameters: [addr, BigInt.from(data)],
      ),
      fetchChainIdFromNetworkId: true,
    );
    print(hash);
    getTransactionReceipt(hash);
  }
}

class PMain extends StatelessWidget {
  PMain();
  @override
  Widget build(BuildContext context) {
    SAddress saddress = Provider.of<SAddress>(context);

    return IStore(
      providers: [
        ChangeNotifierProvider(
          create: (_) => _IStore(
            address: saddress.data.address,
            private: saddress.data.private,
          ),
        ),
      ],
      builder: (BuildContext context) {
        _IStore store = Provider.of<_IStore>(context);
        
        return Scaffold(
          appBar: AppBar(
            title: Text("资产"),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                // Row(
                //   crossAxisAlignment: CrossAxisAlignment.start,
                //   children: <Widget>[
                //     Icon(Icons.ac_unit),
                //     Expanded(
                //       child: Wrap(
                //         spacing: 12,
                //         runSpacing: 5,
                //         children: <Widget>[
                //           Text("111"),
                //           Text("111"),
                //           Text("111"),
                //           Text("111"),
                //           Text("111"),
                //           Text("111"),
                //           Text("111"),
                //           Text("111"),
                //           Text("111"),
                //           Text("111"),
                //           Text("111"),
                //           Text("111"),
                //           Text("111"),
                //           Text("111"),
                //           Text("111"),
                //           Text("111"),
                //           Text("111"),
                //         ],
                //       ),
                //     )
                //   ],
                // )
                Text("当前账户ETH余额：${store.eth}"),
                Text("当前账户USDT余额：${store.usdt}"),
                RaisedButton(
                  onPressed: store.reload,
                  child: Text("刷新"),
                ),
                RaisedButton(
                  onPressed: store.sendTransaction,
                  child: Text("转帐ETH"),
                ),
                RaisedButton(
                  onPressed: store.sendUSDT,
                  child: Text("转帐USDT"),
                ),
                RaisedButton(
                  onPressed: saddress.delData,
                  child: Text("删除当前"),
                ),
                // RaisedButton(
                //   onPressed: CRouter.pWebView,
                //   child: Text("webview"),
                // ),
              ],
            ),
          ),
        );
      },
    );
  }
}
